//
//  authUser.m
//  HappyStore
//
//  Created by 点点充 on 16/1/26.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "authUser.h"

@interface authUser ()
{
    UITextField *tfName;
    UITextField *tfNumber;
    
    UIButton *btnZ;
    UIButton *btnF;
    
    UIImage *imgZ;
    UIImage *imgF;
    
    
    BOOL selectedZOrF;
}

@end

@implementation authUser

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"实名认证";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
-(void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            return 166;
        }
            break;
        case 1:
        {
            if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==1 ) {//个人
                return 345;
            }else if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 2 ){//企业
                return 225;
            }else {
                return 190;
            }
        }
            break;
        default:
            return 120;
            break;
    }
    return 600;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellHeader = @"cellHeader";
    static NSString *cellBottom = @"cellBottom";
    static NSString *cellMain = @"cellMain";//个人
    static NSString *cellQiye = @"cellQiye";//企业
    static NSString *cellZhengFu = @"cellZhengFu";
    
    UITableViewCell *cell;
    
    switch (indexPath.row) {
        case 0:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:cellHeader forIndexPath:indexPath];
            UIImageView *imgHeader = [cell viewWithTag:10];
            imgHeader.layer.masksToBounds = YES;
            imgHeader.layer.cornerRadius = 35;
            [imgHeader sd_setImageWithURL:[NSURL URLWithString:_strHeaderURl] placeholderImage:[UIImage imageNamed:@"btn_my_touxiang"]];
            
            UILabel *labName = [cell viewWithTag:11];
            labName.text = _strUserName;
        }
            break;
        case 1:
        {
            if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==1 ) {//个人
                cell = [tableView dequeueReusableCellWithIdentifier:cellMain forIndexPath:indexPath];
                tfName = [cell viewWithTag:12];
                
                tfNumber = [cell viewWithTag:13];
                
                btnZ = [cell viewWithTag:14];
                [btnZ addTarget:self action:@selector(btnClickPhoto1) forControlEvents:UIControlEventTouchUpInside];
                
                btnF = [cell viewWithTag:15];
                [btnF addTarget:self action:@selector(btnClickPhoto2) forControlEvents:UIControlEventTouchUpInside];
                
                
            }else if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 2 ){//企业
                cell = [tableView dequeueReusableCellWithIdentifier:cellQiye forIndexPath:indexPath];
                tfName = [cell viewWithTag:12];
                
                tfNumber = [cell viewWithTag:13];
                
                btnZ = [cell viewWithTag:14];
                [btnZ addTarget:self action:@selector(btnClickPhoto1) forControlEvents:UIControlEventTouchUpInside];
                
            }else {
                cell = [tableView dequeueReusableCellWithIdentifier:cellZhengFu forIndexPath:indexPath];
                tfName = [cell viewWithTag:12];
                
                btnZ = [cell viewWithTag:14];
                [btnZ addTarget:self action:@selector(btnClickPhoto1) forControlEvents:UIControlEventTouchUpInside];
            }
        }
            break;
        case 2:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:cellBottom forIndexPath:indexPath];
            UIButton *btnOK = [cell viewWithTag:16];
            btnOK.layer.masksToBounds = YES;
            btnOK.layer.cornerRadius = 5.f;
            [btnOK addTarget:self action:@selector(btnClickOK) forControlEvents:UIControlEventTouchUpInside];
        }
            break;
    }
    
    
    
   
    
    
    
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    
}

#pragma mark - 正面
- (void)btnClickPhoto1
{
    selectedZOrF = YES;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"照片选择"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相机",@"相册", nil];
    [actionSheet showInView:self.view];
}

#pragma mark - 反面
- (void)btnClickPhoto2
{
    selectedZOrF = NO;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"照片选择"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相机",@"相册", nil];
    [actionSheet showInView:self.view];
}



#pragma mark - 选择照片
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    pickerImage.delegate = self;
    pickerImage.allowsEditing = YES;//设置可编辑
    switch (buttonIndex) {
        case 0:
        {
            NSLog(@"相机");
            pickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 1:
        {
            NSLog(@"相册");
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 2:
        {
            NSLog(@"取消");
        }
            break;
    }
    
}

//点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //    [_btnUserImg setImage:image forState:UIControlStateNormal];
    //    _btnUserImg.layer.masksToBounds = YES;
    //    _btnUserImg.layer.cornerRadius = 20.0;
    /* 此处info 有六个值
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
     */
    // 保存图片至本地，方法见下文
    //    NSString *strName = [NSString stringWithFormat:@"%@.jpg",[self dateString]];
    //    [self saveImage:image withName:strName];
    
    if (selectedZOrF) {
        //正
        [btnZ setImage:image forState:UIControlStateNormal];
        imgZ = image;
    }else {
        [btnF setImage:image forState:UIControlStateNormal];
        imgF = image;
    }
    
    
}

//点击cancel 调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.1);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}


#pragma mark 照片的时间名称
- (NSString*)dateString
{
    NSMutableString*string=[[NSMutableString alloc] init];
    NSDate*dayDate=[NSDate date];
    NSDateFormatter*dayFormatter=[[NSDateFormatter alloc] init];
    [dayFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStrings= [dayFormatter stringFromDate:dayDate];
    NSArray*dayArray=[dateStrings componentsSeparatedByString:@"-"];
    for (int i=0; i<[dayArray count]; i++) {
        [string appendFormat:@"%@",[dayArray objectAtIndex:i]];
    }
    NSDate*timeDate=[NSDate date];
    NSDateFormatter*timeFormatter=[[NSDateFormatter alloc] init];
    [timeFormatter setDateFormat:@"HH:mm:ss:SSS"];
    NSString *timeString= [timeFormatter stringFromDate:timeDate];
    NSArray*timeArray=[timeString componentsSeparatedByString:@":"];
    for (int i=0; i<[timeArray count]; i++) {
        [string appendFormat:@"%@",[timeArray objectAtIndex:i]];
    }
    return string;
    
}




#pragma mark - 提交
- (void)btnClickOK
{
    BOOL isOK = YES;
    
    if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==1 ) {//个人
        if (tfName.text.length == 0) {
            isOK = NO;

            [self showSingleIconBubble:@"请输入真实姓名"];

        }
        if (isOK) {
            isOK = [tfNumber.text isValidIdCardNum];
            if (!isOK) {
               [self showSingleIconBubble:@"请输入正确的身份证号码"];

            }
        }
        if (isOK) {
            if (imgZ == nil || imgF == nil) {
                [self showSingleIconBubble:@"请添加身份证照片"];

            }
        }
    }else if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 2 ){//企业
        if (tfName.text.length == 0) {
            isOK = NO;
            [self showSingleIconBubble:@"请输入企业名称"];

        }
        if (isOK && tfNumber.text.length == 0) {
            isOK = [tfNumber.text isValidIdCardNum];
           [self showSingleIconBubble:@"请输入社会信用号码"];

        }
        if (isOK && imgZ == nil) {
            [self showSingleIconBubble:@"请添加营业执照副本"];

        }
    }else {
        if (tfName.text.length == 0) {
            isOK = NO;
            [self showSingleIconBubble:@"请输入机构名称"];

        }
        if (isOK && imgZ == nil) {
            [self showSingleIconBubble:@"请添加照片"];

        }
    }
    
    
    
    
    if (isOK) {
        //token=验证用户&userId=用户id&userType=用户类型 （1-个人 2-企业 3-政府）&trueName=真实姓名&trueCard=身份证号
        [self showRoundProgressWithTitle:@"请稍等..."];
        NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"usertype"] forKey:@"userType"];//用户类型
        
        if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==1 ) {//个人
            [muDicParameters setObject:tfName.text forKey:@"trueName"];//真实姓名
            [muDicParameters setObject:tfNumber.text forKey:@"trueCard"];//身份证号
        }else if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 2 ){//企业token=验证用户&userId=用户id&userType=用户类型（1-个人 2-企业 3-政府）&companyName=企业真实名称&companyLicenseNo=营业执照号 参数说明：photo-为图片
            [muDicParameters setObject:tfName.text forKey:@"companyName"];//企业真实名称
            [muDicParameters setObject:tfNumber.text forKey:@"companyLicenseNo"];//营业执照号
            
        }else {
            //token=验证用户&userId=用户id&userType=用户类型（1-个人 2-企业 3-政府）&goveName=政府名称 参数说明：files-为图片
            [muDicParameters setObject:tfName.text forKey:@"goveName"];//政府名称
        }
        
        
        
        NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"authUser_app_myHome.im.lensum"];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        [manager POST:strURl parameters:muDicParameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] ==1 ) {//个人
                // 压缩
                NSMutableArray *aryImg = [NSMutableArray arrayWithObjects:imgZ,imgF, nil];
                NSMutableArray *muSaveFull = [NSMutableArray array];
                for (int i = 0; i<aryImg.count; i++) {
                    UIImage *image = aryImg[i];
                    NSString *strName1 = [NSString stringWithFormat:@"%@.png",[self dateString]];
                    [self saveImage:image withName:strName1];
                    NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:strName1];
                    [muSaveFull addObject:fullPath1];
                }
                
                
                NSString *zippedPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",[self dateString]]];
                
                BOOL isSucee = [SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:muSaveFull];
                if (isSucee) {
                    NSData *data1 = [NSData dataWithContentsOfFile:zippedPath];
                    [formData appendPartWithFileData:data1 name:@"photos" fileName:@"photos.zip" mimeType:@"zip"];
                }
            }else if([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 2 ){//企业
                NSData *imageData = UIImageJPEGRepresentation(imgZ, 0.5);
                [formData appendPartWithFileData:imageData name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
            }else {
                NSData *imageData = UIImageJPEGRepresentation(imgZ, 0.5);
                [formData appendPartWithFileData:imageData name:@"files" fileName:@"files.jpg" mimeType:@"image/jpeg"];
            }
            
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
            

            
//            NSLog(@"%@",dicInfo);
            if ([dicInfo[@"result"] integerValue] == 1) {
                [self performSelector:@selector(dismissVC) withObject:nil afterDelay:kHideHudDelay];

                [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
            }else {

                [self showSingleIconBubble:dicInfo[@"msg"]];
            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            [self showSingleIconBubble:error.localizedDescription];
        }];
        
    }
}

- (void)dismissVC
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
